# from flask import Blueprint,request,jsonify,make_response
# from application.models.users.user import *
# from util.myredis import r
# user_blue = Blueprint('user', __name__)
# import time
# import json
# import redis
# import random
# from util.captcha.captcha import captcha
# #测试
# @user_blue.route("/test")
# def test():
#     id = request.args.get("id")
#     return jsonify({"code":200,"id":id})
#
# @user_blue.route("/getcode")
# def get_img():
#     name,text,img=captcha.generate_captcha()
#     uuid=request.args.get('uuid')
#     r.str_add(uuid,text)
#     cls = redis.Redis(host='127.0.0.1')
#     print(">>>>>>>>>>>>>>>>",cls.get(uuid))
#     res=make_response(img)
#     res.headers['Content-Type']="image/jpg"
#     return res
# # 获取图片验证码
# # @user_blue.route("/getcode")
# # def getcode():
# #     #生成图片验证码 text文字， image图片流
# #     name,text,image = captcha.generate_captcha()
# #     #从页面获取uuid做为redis key
# #     uuid = str(request.args.get('uuid'))
# #     #存入redis
# #     r.str_add(uuid,str(text),60)
# #     #以流的方式生成图片验证码
# #     res = make_response(image)
# #     res.headers["Content-Type"] = "image/jpg"
# #     # 存入redis
# #     # r.set_str(uuid,text)
# #     return res
#
# @user_blue.route("/sendSmsCode",methods=["POST"])
# def sendSmsCode():
#     data = request.data
#     if data:
#         data = json.loads(data)
#         print(data)
#         uuid = data['uuid']
#         print(uuid)
#         piccode = data['piccode']
#         print(piccode,'>>>>>>>>>>>>>>>>')
#         mobile = data['mobile']
#         value = r.str_get(uuid)
#         value1 = value.decode()
#         print(value1)
#         if value:
#             if piccode.lower()==value1.lower():
#                 mcode = r.str_get(mobile)
#                 if mcode:
#                     return jsonify({'code':10012,'msg':'一分钟内不能重复发'})
#                 scode = random.randint(10000,99999)
#                 flag = sendSmsCode(mobile,scode)
#                 if flag:
#                     r.str_setex(mobile,scode,60)
#                     r.del_key(uuid)
#                     return jsonify({'code':200,'msg':'发送成功'})
#                 else:
#                     return jsonify({'code':10013,'msg':'发送验证码错误'})
#             else:
#                 return jsonify({'code':10011,'msg':'图片验证码错误'})
#         else:
#             return jsonify({'code':10010,'msg':'图片验证码不存在'})
#
#
# # 发送短信接口
# @user_blue.route("/login",methods=['POST'])
# def login():
#     data = request.data
#     if data:
#         data = json.loads(data)
#         mcode = data["code"]
#         mobile = data["mobile"]
#         code = r.str_get(mobile)
#         if code:
#             if int(code)==int(mcode):
#                 user = UsersModel.query.filter_by(UsersModel.mobile==mobile).first()
#                 if user:
#                     r.del_str(mobile)
#                 else:
#                     u = UsersModel(mobile,nikename=mobile)
#                     db.session.add(u)
#                     db.session.commit()
#                     user = UsersModel.query.filter_by(UsersModel.mobile==mobile).first()
#                 # token = myjwt.encode(data={"data":{"uid":user.id,'exp':int(time.time())}})
#                 token = str(random.randint(100,1000))
#                 return jsonify({"code":200,"token":token,"userid":user.id})
#         else:
#             return jsonify({"code":10021,"mes":"验证码错误"})
#     else:
#         return jsonify({"code":10020,"mes":""})

# import jwt
# from flask import Blueprint, jsonify, current_app ,send_file
# from flask_restful import Api, Resource,reqparse
# from util.comm import send_message
# from util.myredis import r
# from application.models.users.user import UsersModel,db
# from captcha.image import ImageCaptcha
# user_blue = Blueprint('user_blue', __name__, url_prefix='/')
# api = Api(user_blue)
# import random
# import time
#
# # 图片验证码
# class ImgView(Resource):
#     def get(self,uuid):
#         img = ImageCaptcha()
#         code = random.randint(1000,9999)
#         code1 = str(code)
#         img_png = img.generate(code1)
#         r.ser_add(uuid,code1,3600)
#         return send_file(img_png,mimetype="png")
# api.add_resource(ImgView,'/img/<uuid>')
#
# class SendSmsCode(Resource):
#     def post(self):
#         req = reqparse.RequestParser()
#         req.add_argument('uuid')
#         req.add_argument('mobile')
#         req.add_argument('piccode')
#         args = req.parse_args()
#         print(args['piccode'])
#
#         # 从redis中取出来 图片验证码
#         value = r.str_get('uuid='+ args['uuid'])
#         if value:
#             if args['piccode'] == value.decode():
#                 # 验证一分钟内只能发一次
#                 mcode = r.str_get(args['mobile'])
#                 if mcode:
#                     return jsonify({'code':10012,'msg':'一分钟内不能重复发'})
#                 # 调用短信平台
#                 # 生成5位随机数
#                 smscode = str(random.randint(1000, 9999))
#                 flag = send_message(args['mobile'], smscode)
#                 if flag:
#                     # 手机验证码存入redis
#                     r.ser_add(args['mobile'],smscode,60)
#                     # 删除图片验证码
#                     r.del_str(args['uuid'])
#                     # 返回结果
#                     return jsonify({'code':200,'msg':'发送成功'})
#                 else:
#                     return jsonify({'code': 10013, 'msg': '发送验证码失败'})
#             else:
#                 return jsonify({'code':10011,'msg':'图片验证码错误'})
#         else:
#             return jsonify({'code': 10010, 'msg': '图片验证码不存在'})
# api.add_resource(SendSmsCode,'/sendSmsCode')
#
#
# # 登录接口
# class LoginView(Resource):
#     def post(self):
#         req = reqparse.RequestParser()
#         req.add_argument('smscode')
#         req.add_argument('mobile')
#         args = req.parse_args()
#         # 判断数据是否存在
#         if not all([args['smscode'],args['mobile']]):
#             return jsonify({
#                 'code':400,
#                 'msg':'数据不完整'
#             })
#         # 从redis中取出  验证码
#         code = r.str_get(args['mobile'])
#         if code:
#             print(code,55555)
#             # 判断验证码是否相同
#             if int(code) == int(args['smscode']):
#                 user = UsersModel.query.filter(UsersModel.mobile == args['mobile']).first()
#                 print(user,111111)
#                 # 如果相同 删除验证码（为了节约内存）
#                 # 否则  存入到用户表中
#                 if user:
#                     r.del_str(args['mobile'])
#                 else:
#                     u = UsersModel(mobile=args['mobile'],nikename=args['mobile'])
#                     db.session.add(u)
#                     db.session.commit()
#                     user = UsersModel.query.filter(UsersModel.mobile == args['mobile']).first()
#                 # 生成一个token  key加盐
#                 # 返回token给前端  用户id也返回过去
#                 key = current_app.config.get('SECRET_KEY')
#                 token = jwt.encode({
#                     'user_id':user.id,
#                     'exp': int(time.time()) + 180
#                 },key,algorithm='HS256')
#                 return jsonify({
#                     'code':200,
#                     'msg':'登录成功',
#                     'token':token,
#                     'user_id':user.id
#                 })
#             else:
#                 return jsonify({'code':400,'msg':'验证码错误'})
#         else:
#             return jsonify({'code':400,'msg':'验证码已过期'})
# api.add_resource(LoginView,'/login')
import random
import redis
from flask import Blueprint, send_file, make_response
from flask_restful import Resource
from ronglian_sms_sdk import SmsSDK
from util.captcha.captcha import captcha
from util.myredis import r
import json
from util.comm import send_message
from app import db
import functools
import token
from application.models.users.user import UsersModel
from flask import Blueprint,request,jsonify
from util.myjwt import mjwt
user_blue = Blueprint("userblue",__name__)
from captcha.image import ImageCaptcha
#权限认证
# def islogin(func):
#     @functools.wraps(func)
#     def wrapper():
#         # #设置一个白名单
#         # whitelist = ["/getcode","/sendSmsCode","/login"]
#         # url = request.path
#         # if url not in whitelist:
#         #     #判断当前访问的url是否在白名单中，如果不在验证token
#         #     try:
#         #         token = request.headers["token"]
#         #         #获取token
#         #         #调用jwt封装好的check_token对比
#         #         flag = mjwt.check_token(token)
#         #         if flag == True:
#         #             # 如果通过验证过期时间
#         #             payload = mjwt.jwt_decode(token)
#         #             now = time.time()
#         #             tnow = payload["data"]["exp"]
#         #             if int(now)-int(tnow)>3600:
#         #                 return jsonify({"code":401,"mes":"token已经过期"})
#         #         else:
#         #             return jsonify({"code":401,"mes":"token被篡改"})
#         #     except:
#         #         return jsonify({"code":401,"mes":"没获取到token "})
#         # func()
#         #权限验证判断，如果有问题返回
#         return func
#     return wrapper

#测试
# def islogin(func):
#     def wrapper():
#         print("接口执行前操作")
#         func()
#         return func
#     return wrapper()

#测试
def islogin(type):
    def pemistion(func):
        def wrapper():
            func()
            if type == 1:
                return redirect("http://www.baidu.com")
            else:
                return redirect("http://www.jd.com")
        return wrapper
    return pemistion

@user_blue.route("/test")
@islogin(1)
def test():
    time.sleep(3)
    return jsonify({"code":200,"mes":"mes"})

@user_blue.route('/getcode')
@islogin(2)
def get_img():
    name,text,img=captcha.generate_captcha()
    uuid=request.args.get('uuid')
    r.str_add(uuid,text)
    cls = redis.Redis(host='127.0.0.1')
    print(">>>>>>>>>>>>>>>>",cls.get(uuid))
    res=make_response(img)
    res.headers['Content-Type']="image/jpg"
    return res

@user_blue.route("/sendSmsCode",methods=["POST"])
def sendSmsCode():
    data = request.data
    # 获取3个参数
    if data:
        data = json.loads(data)
        uuid = data['uuid']
        piccode = data['piccode']
        print(piccode,'>>>>>>>>>>>>>>>>')
        mobile = data['mobile']
        value = r.str_get(uuid)
        value1 = value.decode()
        print(value1)
        if value:
            if piccode.lower()==value1.lower():
                mcode = r.str_get(mobile)
                if mcode:
                    return jsonify({'code':10012,'msg':'一分钟内不能重复发'})
                scode = random.randint(10000,99999)
                flag = send_message(mobile,scode)
                if flag:
                    r.str_setex(mobile,scode,60)
                    r.del_key(uuid)
                    return jsonify({'code':200,'msg':'发送成功'})
                else:
                    return jsonify({'code':10013,'msg':'发送验证码错误'})
            else:
                return jsonify({'code':10011,'msg':'图片验证码错误'})

        else:
            return jsonify({'code':10010,'msg':'图片验证码不存在'})

import time
# 发送短信接口
@user_blue.route("/login",methods=['POST'])
def login():
    data = request.data
    if data:
        data = json.loads(data)
        mcode = data["code"]
        mobile = data["mobile"]
        code = r.str_get(mobile)
        if code:
            if int(code)==int(mcode):
                user = UsersModel.query.filter(UsersModel.mobile==mobile).first()
                if user:
                    r.del_str(mobile)
                else:
                    u = UsersModel(mobile=mobile,nikename=mobile)
                    db.session.add(u)
                    db.session.commit()
                    user = UsersModel.query.filter(UsersModel.mobile==mobile).first()
                token = myjwt.jwt_encode({"user_id":user.id,'exp':int(time.time())+60})
                # token = str(random.randint(100,1000))
                return jsonify({"code":200,"msg":"发送成功","token":token,"userid":user.id})
        else:
            return jsonify({"code":10021,"mes":"验证码不存在"})
    else:
        return jsonify({"code":10020,"mes":"数据不完整"})







